package com.hxd.otc.common;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.hxd.otc.api.Constant;
import com.hxd.otc.common.enums.CardLevelEnum;
import com.hxd.otc.common.enums.ExValidType;
import com.hxd.otc.common.enums.IdCardStatusEnum;
import com.hxd.otc.common.enums.RoleTypeEnum;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.login.bean.AccountBean;
import com.hxd.otc.utils.SpUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.hyphenate.HyphenateKeFuUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import io.rong.imkit.RongIM;

import static com.hxd.otc.common.SpConfig.Cache.USER_INFO;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/6/12 17:10
 * 描  述 :  用户信息工具类
 * <p>
 * }
 */
public class UserHelper {

    public static String mToken = "";

    static {
        getToken();
    }

    /**
     * 仅用于登录时更新用户信息，欲直接操作用户信息，使用{@link  UserHelper#updateUserInfo(AccountBean)}
     *
     * @param accountBean 登录成功后的结果值
     */
    public static void putLoginResult(AccountBean accountBean) {
        if (accountBean == null) return;
        mToken = StringUtil.emptyIfNull(accountBean.getToken());
        updateUserInfo(accountBean);
    }


    /**
     * 更新用户信息
     * <p>
     * 注意：在用户信息更新后会通过EventBus发送event，事件对象为AccountBean
     *
     * @param newAccountBean
     */
    public static void updateUserInfo(AccountBean newAccountBean) {
        SpUtil.PERMANENT.putBoolean(SpConfig.MD5Encryption.MD5_ENCRYPTION, true);
        SpUtil.CACHE.putObject(USER_INFO, newAccountBean,  SpUtil.PERMANENT.getBoolean(SpConfig.MD5Encryption.MD5_ENCRYPTION,false));
        EventBus.getDefault().post(new Event.UserInfoUpdateEvent(newAccountBean));
    }

    /**
     * 获取用户信息
     *
     * @return 返回结果不为空，在用户信息为空时，返回一个新建对象
     */
    public static AccountBean getUserInfo() {
        AccountBean userInfo = SpUtil.CACHE.getObject(USER_INFO, AccountBean.class, SpUtil.PERMANENT.getBoolean(SpConfig.MD5Encryption.MD5_ENCRYPTION, false));
        if (userInfo == null) userInfo = new AccountBean();
        return userInfo;
    }

    public static String getNickName() {
        return StringUtil.emptyIfNull(getUserInfo().getNickName());
    }

    public static String getAvatar() {
        return "";
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public static String getId() {
        return StringUtil.emptyIfNull(getUserInfo().getId());
    }

    /**
     * 更新token
     *
     * @param token
     */
    public static void updateToken(@NonNull String token) {
        token = TextUtils.isEmpty(token) ? "" : token;

        AccountBean userInfo = getUserInfo();
        userInfo.setToken(token);
        updateUserInfo(userInfo);
    }

    public static String getToken() {
        if (TextUtils.isEmpty(mToken)) {
            mToken = StringUtil.emptyIfNull(getUserInfo().getToken());
        }
        return StringUtil.emptyIfNull(getUserInfo().getToken());
    }

    public static void updateRongCloudToken(String rongCloudToken) {
        AccountBean userInfo = getUserInfo();
        userInfo.setRongColudToken(rongCloudToken);
        updateUserInfo(userInfo);
    }

    public static String getRongCloudToken() {
        return getUserInfo().getRongColudToken();
    }

    /**
     * 清空用户信息
     */
    public static void cleanUserData() {
        updateUserInfo(new AccountBean());//添加这可以保证在退出登录时能通知观测的页面更新展示，避免导致有展示登录信息却还需要重新登录的问题
        SpUtil.CACHE.clear();
        mToken = "";
    }

    /**
     * 退出登陆
     *
     * @param activity
     */
    public static void logout(Activity activity) {
        logoutButNoSkipLogin();
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }

    /**
     * 退出当前用户，但是不跳转登录
     */
    public static void logoutButNoSkipLogin() {
        cleanUserData();
        RongIM.getInstance().logout();
        HyphenateKeFuUtil.getInstance().logout();
    }

    /**
     * 是否登录
     */
    public static boolean isLogin() {
        return !TextUtils.isEmpty(getToken());
    }

    /**
     * 是否已经绑定手机号
     */
    public static boolean isBoundPhone() {
        return !TextUtils.isEmpty(getMobile());
    }

    /**
     * 获取当前用户手机号
     */
    public static String getMobile() {
        return StringUtil.emptyIfNull(getUserInfo().getMobile());
    }

    /**
     * 更新手机号
     *
     * @param mobile
     */
    public static void updateMobile(String mobile) {
        AccountBean userInfo = getUserInfo();
        userInfo.setMobile(mobile);
        updateUserInfo(userInfo);
    }

    /**
     * 是否已经绑定邮箱
     */
    public static boolean isBoundEmail() {
        return !TextUtils.isEmpty(getEmail());
    }

    /**
     * 获取当前用户邮箱
     */
    public static String getEmail() {
        return StringUtil.emptyIfNull(getUserInfo().getMail());
    }

    /**
     * 修改绑定邮箱
     *
     * @param email
     */
    public static void updateEmail(String email) {
        AccountBean userInfo = getUserInfo();
        userInfo.setMail(email);
        updateUserInfo(userInfo);
    }

    /**
     * @param nickName
     */
    public static void updateNickName(String nickName) {
        AccountBean userInfo = getUserInfo();
        userInfo.setNickName(nickName);
        updateUserInfo(userInfo);
    }

    /**
     * 是否已经设置交易密码
     * 0.已设置，1.未设置
     */
    public static boolean isSetPayPassword() {
        AccountBean userInfo = getUserInfo();
        return "true".equals(userInfo.getExPassword());
    }

    /**
     * 修改是否设置交易密码
     *
     * @param isHasPayPassword
     */
    public static void updateHasPayPassword(boolean isHasPayPassword) {
        AccountBean userInfo = getUserInfo();
        userInfo.setExPassword(String.valueOf(isHasPayPassword));
        updateUserInfo(userInfo);
    }

    /**
     * 获取实名认证状态
     *
     * @return
     */
    public static IdCardStatusEnum getCardStatus() {
        return IdCardStatusEnum.getIDCardStatusEnum(getUserInfo().getCardStatus());
    }

    /**
     * 更新实名认证状态
     *
     * @param idCardStatusEnum
     */
    public static void updateCardStatus(IdCardStatusEnum idCardStatusEnum) {
        AccountBean userInfo = getUserInfo();
        userInfo.setCardStatus(idCardStatusEnum.getCode());

        //进行认证等级更新
        if (IdCardStatusEnum.V1_Verified.equals(idCardStatusEnum)) {
            userInfo.setCardLevel(CardLevelEnum.LEVEL_1.getValue());
        } else if (IdCardStatusEnum.V2_Verified.equals(idCardStatusEnum)) {
            userInfo.setCardLevel(CardLevelEnum.LEVEL_2.getValue());
        }

        updateUserInfo(userInfo);
    }

    public static CardLevelEnum getCardLevel() {
        return CardLevelEnum.getInstance(getUserInfo().getCardLevel());
    }

    public static void updateCardLevel(CardLevelEnum cardLevelEnum) {
        AccountBean userInfo = getUserInfo();
        userInfo.setCardLevel(cardLevelEnum.getValue());
        updateUserInfo(userInfo);
    }

    /**
     * @return 是否已经V2认证
     */
    public static boolean isV2Verified() {
        return IdCardStatusEnum.V2_Verified.equals(getCardStatus());
    }

    /**
     * @return 是否已经V1认证
     */
    public static boolean isV1Verified() {
        return IdCardStatusEnum.V1_Verified.equals(getCardStatus());
    }

    /**
     * "1"：谷歌验证；"3"：短信验证；"4":"邮箱验证"，其他："用户还没有设置"
     */
    public static ExValidType getExValidType() {
        return ExValidType.getInstanceByType(getUserInfo().getExValidType());
    }

    /**
     * @return 是否已经设置验证方式
     */
    public static boolean isSetExValidType() {
        return !ExValidType.Other.equals(getExValidType());
    }

    /**
     * "1"：谷歌验证；"2"：交易密码验证；其他："用户还没有设置"
     *
     * @param exValidType
     */
    public static void updateExValidType(ExValidType exValidType) {
        AccountBean userInfo = getUserInfo();
        userInfo.setExValidType(exValidType.getValidType());
        updateUserInfo(userInfo);
    }

    /**
     * 是否已经设置谷歌认证
     */
    public static boolean isSetGoogleAuth() {
        AccountBean userInfo = getUserInfo();
        return userInfo.isGoogleAuth();
    }

    /**
     * 更新谷歌认证状态
     */
    public static void updateGoogleAuth(boolean isAuth) {
        AccountBean userInfo = getUserInfo();
        userInfo.setGoogleAuth(isAuth);
        updateUserInfo(userInfo);
    }

    /**
     * 获取正式姓名
     *
     * @return
     */
    public static String getRealName() {
        return StringUtil.emptyIfNull(getUserInfo().getRealName());
    }

    /**
     * @return 是否是广告商
     */
    public static boolean isSilver() {
        String tag = getUserInfo().getTag();
        return !TextUtils.isEmpty(tag) && tag.startsWith("OTC-GGS");
    }

    /**
     * @return 是否时商户
     */
    public static boolean isMerchant() {
        String tag = getUserInfo().getTag();
        return !TextUtils.isEmpty(tag) && (tag.startsWith("OTC-SH") || tag.startsWith("OTC-SJ"));
    }

    public static void setTag(String tag) {
        AccountBean userInfo = getUserInfo();
        userInfo.setTag(tag);
        UserHelper.updateUserInfo(userInfo);
    }

    public static void putName(String name) {

    }

    public static String getInviteCode() {
        AccountBean userInfo = getUserInfo();
        return StringUtil.emptyIfNull(userInfo.getInviteCode());
    }

    public static String getNationalCode() {
        return Constant.DEFAULT_NATIONAL_CODE;
    }

    public static void updatePrepaidRechargeHistories(String phoneNumber) {
        if (phoneNumber == null) return;
        String mobile = phoneNumber.trim().replace(" ", "");
        if (TextUtils.isEmpty(mobile)) return;
        HashMap<String, ArrayList<String>> map = getAllPrepaidRechargeHistories();
        String userId = UserHelper.getId();
        ArrayList<String> list = map.get(userId);
        list = (list == null ? new ArrayList<String>() : list);
        if (list.contains(mobile)) {
            list.remove(mobile);
        }
        list.add(0, phoneNumber);
        map.put(userId, list);
        SpUtil.PERMANENT.putObject(SpConfig.Permanent.PREPAID_RECHARGE_HISTORIES, map);
    }

    public static void clearCurUserPrepaidRechargeHistories() {
        HashMap<String, ArrayList<String>> map = getAllPrepaidRechargeHistories();
        map.put(getId(), new ArrayList<String>());
        SpUtil.PERMANENT.putObject(SpConfig.Permanent.PREPAID_RECHARGE_HISTORIES, map);
    }

    public static ArrayList<String> getCurUserPrepaidRechargeHistories() {
        HashMap<String, ArrayList<String>> map = getAllPrepaidRechargeHistories();
        if (map.size() == 0) return new ArrayList<>();
        ArrayList<String> list = map.get(UserHelper.getId());
        return list == null ? new ArrayList<String>() : list;
    }

    public static HashMap<String, ArrayList<String>> getAllPrepaidRechargeHistories() {
        HashMap<String, ArrayList<String>> map = SpUtil.PERMANENT.getObject(SpConfig.Permanent.PREPAID_RECHARGE_HISTORIES, new TypeToken<HashMap<String, ArrayList<String>>>() {
        }.getType());
        if (map == null) return new HashMap<>();
        return map;
    }

    public static String getRecommendedAddress() {
        return ApiConstants.URL_OF_SHARE + UserHelper.getInviteCode();
    }

    /**
     * @return 是否是无感支付广告商
     */
    public static boolean isNonInductivePaySilver() {
        return RoleTypeEnum.NonInductiveSliver.equals(getUserInfo().getRoleType());
    }

    /**
     * @return 用户角色
     */
    public static RoleTypeEnum getRoleType() {
        return getUserInfo().getRoleType();
    }

    /**
     * 更新用户角色
     *
     * @param role
     */
    public static void updateRoleType(String role) {
        AccountBean userInfo = getUserInfo();
        userInfo.setRole(role);
        updateUserInfo(userInfo);
    }

    public static String getRoleLoginSource() {
        return isNonInductivePaySilver() ? "otc-easypay" : "otc";
    }
}
